package com.learning.arrlist;

public class ArrSample {
	protected ArrNode head;

	public ArrSample() {
	}

	public boolean isEmpty() {
		return head == null;
	}

	public Object first() {
		return head.infor;
	}

	public ArrNode head() {
		return head;
	}

	public void printAll(java.io.PrintStream out) {
		for (ArrNode tmp = head; tmp != null; tmp = tmp.next){
			out.print(tmp.infor.toString());
			System.out.println(tmp.infor.toString());
		}
	}

	public void add(Object el) {
		head = new ArrNode(el, head);
	}
	public void addToTail(Object el){
		ArrNode tmp = head;
		if(head==null){
			head=new ArrNode(el, head);
		}
		else{
			while(tmp.next!=null){
				tmp=tmp.next;
			}
			tmp.next= new ArrNode(el, tmp.next);
		}
	}
	public Object find(Object el) {
		ArrNode tmp = head;
		for (; tmp != null && !el.equals(tmp.infor); tmp = tmp.next)
			;
		if (tmp == null)
			return null;
		else
			return tmp.infor;
	}

	public Object deleteHead() { // remove the head and return its info;
		Object el = head.infor;
		head = head.next;
		return el;
	}
	/**
	 * delete tail of linkedlist
	 * @author AnND1
	 * 
	 */
	public void deleteTail(){
		ArrNode prev=null;
		if(head.next==null)
			head=null;
		else{
			ArrNode tmp=head;
			while(tmp.next!=null){
				prev=tmp;
				tmp=tmp.next;
			}
			prev.next=null;
		}
			
	}

	public void delete(Object el) { // find and remove el;
		if (head != null) // if non-empty list;
			if (el.equals(head.infor)) // if head needs to be removed;
				head = head.next;
			else {
				ArrNode pred = head, tmp = head.next;
				for (; tmp != null && !(tmp.infor.equals(el)); pred = pred.next, tmp = tmp.next)
					;
				if (tmp != null) // if found
					pred.next = tmp.next;
			}
	}
}
